package com.lagou.dubbo.impl;/**
 * Created by IntelliJ IDEA.
 * User: Yangdx.
 * Date: 2020/7/25.
 * Time: 8:26.
 * Tags: Code, we are serious.
 */

import com.lagou.dao.AuthCodeDao;
import com.lagou.model.AuthCode;
import com.lagou.model.AuthCodeService;
import com.lagou.model.ValidateResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;

/**
 * @author
 * @create 2020-07-25 8:26
 **/
@Service
public class AuthCodeServiceImpl implements AuthCodeService {

    @Autowired
    private AuthCodeDao authcodeDao;
    @Value("${config.code.validate.expire}")
    private int codeExpireSeconds;

    @Override
    public void createNewCode(String email, String code) {
        long createTime = System.currentTimeMillis();
        long expireTime = createTime + codeExpireSeconds * 1000;

        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        authCode.setCreatetime(new Date(createTime));
        authCode.setExpiretime(new Date(expireTime));

        authcodeDao.save(authCode);
    }

    @Override
    public ValidateResult validateAuthCode(String email, String code) {
        AuthCode latest = authcodeDao.findFirstByEmailOrderByIdDesc(email);
        if (latest == null) return ValidateResult.FAIL;
        if (!latest.getCode().equalsIgnoreCase(code)) return ValidateResult.FAIL;

        long expireTime = latest.getExpiretime().getTime();
        if (expireTime <= System.currentTimeMillis()) return ValidateResult.TIMEOUT;

        return ValidateResult.SUCCESS;
    }
}
